using MediatR;
using Process.Api.Application.Command.BOM;
using Process.BLL;
using Process.DAL;
using Process.ErrorCod;
using Process.Model;

namespace Process.Api.Application.Handler.BOM
{
    public class UpdateBomHandler : IRequestHandler<UpdateBomCommand, ApiResult<int>>
    {
        private readonly IProcessRepository<BomTable> bomRepo;
        private readonly IProcessRepository<BomGoodsRelation> bomGoodsRepo;
        private readonly IProcessRepository<BomFlowRelation> bomFlowRepo;

        public UpdateBomHandler(
            IProcessRepository<BomTable> bomRepo,
            IProcessRepository<BomGoodsRelation> bomGoodsRepo,
            IProcessRepository<BomFlowRelation> bomFlowRepo)
        {
            this.bomRepo = bomRepo;
            this.bomGoodsRepo = bomGoodsRepo;
            this.bomFlowRepo = bomFlowRepo;
        }

        /// <summary>
        /// 更新BOM数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(UpdateBomCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<int>();

            try
            {
                // 验证请求
                if (request.Id <= 0)
                {
                    result.Code = ErrorStatus.Error;
                    result.Message = "BOM ID无效";
                    result.Data = 0;
                    return result;
                }

                // 查找要更新的BOM
                var bom = bomRepo.GetAllAsync().FirstOrDefault(x => x.Id == request.Id && !x.IsDelete);
                if (bom == null)
                {
                    result.Code = ErrorStatus.Error;
                    result.Message = $"BOM不存在或已被删除 (ID: {request.Id})";
                    result.Data = 0;
                    return result;
                }

                // 检查BOM编号是否重复（排除当前记录）
                var existingBom = bomRepo.GetAllAsync().FirstOrDefault(x => 
                    x.BOMCode == request.BOMCode && 
                    x.Id != request.Id && 
                    !x.IsDelete);
                if (existingBom != null)
                {
                    result.Code = ErrorStatus.Error;
                    result.Message = "BOM编号已存在，请使用其他编号";
                    result.Data = 0;
                    return result;
                }

                // 更新BOM基本信息
                bom.BOMCode = request.BOMCode;
                bom.BOMTitle = request.BOMTitle;
                bom.ProductGoodsId = request.ProductGoodsId;
                bom.ProductsCode = request.ProductsCode;
                bom.ProductsName = request.ProductsName;
                bom.ProductsModel = request.ProductsModel;
                bom.ProductsUnit = request.ProductsUnit;
                bom.Brand = request.Brand;
                bom.Status = request.Status;
                bom.Version = request.Version;
                bom.Output = request.Output;
                bom.Desc = request.Desc;
                bom.UpdateTime = DateTime.Now;
                // 可以设置更新人，如果有用户信息的话
                // bom.Updater = currentUser;

                // 更新BOM主表
                var bomUpdateResult = await bomRepo.UpdateAsync(bom);
                if (bomUpdateResult <= 0)
                {
                    result.Code = ErrorStatus.Error;
                    result.Message = "更新BOM基本信息失败";
                    result.Data = 0;
                    return result;
                }

                // 智能关系管理：根据KeepExistingRelations标志和关系数组状态决定是否更新关系
                if (request.KeepExistingRelations && 
                    (!request.GoodsRelations?.Any() == true) && 
                    (!request.FlowRelations?.Any() == true))
                {
                    // 保留原有关系，只更新基本信息
                    result.Code = ErrorStatus.Success;
                    result.Message = "更新BOM基本信息成功，保留原有关系";
                    result.Data = bomUpdateResult;
                    return result;
                }

                // 需要更新关系时，先删除旧关系再添加新关系
                // 删除旧的配件关系
                var oldGoodsRelations = bomGoodsRepo.GetAllAsync()
                    .Where(x => x.BomTableId == request.Id)
                    .ToList();
                foreach (var relation in oldGoodsRelations)
                {
                    await bomGoodsRepo.DeleteAsync(relation);
                }

                // 删除旧的工艺流程关系
                var oldFlowRelations = bomFlowRepo.GetAllAsync()
                    .Where(x => x.BomTableId == request.Id)
                    .ToList();
                foreach (var relation in oldFlowRelations)
                {
                    await bomFlowRepo.DeleteAsync(relation);
                }

                // 添加新的配件关系
                if (request.GoodsRelations != null && request.GoodsRelations.Any())
                {
                    foreach (var goodsRelation in request.GoodsRelations)
                    {
                        var newGoodsRelation = new BomGoodsRelation
                        {
                            BomTableId = request.Id,
                            GoodsinfoId = goodsRelation.GoodsinfoId
                        };
                        await bomGoodsRepo.CreateAsync(newGoodsRelation);
                    }
                }

                // 添加新的工艺流程关系
                if (request.FlowRelations != null && request.FlowRelations.Any())
                {
                    foreach (var flowRelation in request.FlowRelations)
                    {
                        var newFlowRelation = new BomFlowRelation
                        {
                            BomTableId = request.Id,
                            ProcessFlowId = flowRelation.ProcessFlowId
                        };
                        await bomFlowRepo.CreateAsync(newFlowRelation);
                    }
                }

                result.Code = ErrorStatus.Success;
                result.Message = "更新BOM成功";
                result.Data = bomUpdateResult;
            }
            catch (Exception ex)
            {
                result.Code = ErrorStatus.Error;
                result.Message = $"更新BOM时发生错误: {ex.Message}";
                result.Data = 0;
            }

            return result;
        }
    }
}
